import { IDispatcher, IController, IRoute, IValid } from "../interfaces";
import { AppEvent } from "../event/AppEvent";
import { AppEventName } from "../Define";
import { EventEmitter } from "../event/EventEmitter";

export class Dispatcher extends EventEmitter implements IDispatcher, IValid {

    protected _controllerHashMap: { [name: string]: IController } = {}


    init(): void {
        this.subscribeEvents([new AppEvent(AppEventName.app_dispatch, (data: IRoute) => {
            this.dispatch(data)
        }, this)])
    }
    isValid() {
        return true;
    }
    protected dispatch(route: IRoute) {
        let controller: IController = this.getController(route.controllerName)
        if (controller) {
            let a = controller[route.actionName]
            if (a) {
                a(route.args)
            } else {
                this.triggerEvent(AppEventName.app_error, "Not have action " + route.actionName)
            }
        }

    }

    protected getController(name: string): IController {
        let controller: IController = this._controllerHashMap[name]
        if (!controller) {
            let Controller: any = this.getClassByName(name)
            if (!Controller) {
                this.triggerEvent(AppEventName.app_error, "Not have controller " + name)
                return null;
            }
            controller = new Controller(this._mediator)
            this._controllerHashMap[name] = controller;
        }
        return controller;
    }

    protected getClassByName(name: string): any {
        return null;
    }

}